package XML;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;


/**
 * @Author MJS
 * @Date 2021/9/4 16:00
 * @Description
 */
public class xml {
    public  String format(String unformattedXml) {
        try {
            final Document document = parseXmlFile(unformattedXml);
            OutputFormat format = new OutputFormat(document);
            format.setLineWidth(65);
            format.setIndenting(true);
            format.setIndent(2);
            Writer out = new StringWriter();
            XMLSerializer serializer = new XMLSerializer(out, format);
            serializer.serialize(document);
            return out.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private Document parseXmlFile(String in) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            InputSource is = new InputSource(new StringReader(in));
            return db.parse(is);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (org.xml.sax.SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws Exception{
        String s = "<xml><appid>wx6447c8704bc6350f</appid><mch_id>1601499273</mch_id><nonce_str>OlAbD1qo0HCiyKwS</nonce_str><notify_url>https://wxnotify.sfdy.cn/account/notify/notifyWeiXinRefund</notify_url><out_refund_no>REFUND_FREIGHT@20210904110858cafnsya2</out_refund_no><out_trade_no>20210904110858cafnsya2</out_trade_no><refund_fee>100.0</refund_fee><sign><![CDATA[29E6D6D30DC42B7E93A91418A85A3DBE]]></sign><total_fee>100.0</total_fee><transaction_id>4200001123202109042374480276</transaction_id></xml>";//未格式化前的xml
        System.out.println(new xml().format(s));

    }
}
